#!/usr/bin/env python
# Hello world test
# Purpose: transmit data to the web service
#source code from: http://www.boddie.org.uk/python/HTML.html

import urllib, sys

#Runs an individual test
def runTest(host, testname, senddata, expectedresult):
  print ('executing '+testname+'...');
  message = 'failed'
  try:
    f = urllib.urlopen(host+testname, urllib.urlencode(senddata))
    actual = urllib.unquote(f.read())
    f.close()
    if actual == expectedresult:
      message = 'passed'
    else:
      message = 'failed. actual len: '+str(len(actual))+' expected:'+str(len(expectedresult))+'\n'
      message += 'actual:\n'+actual+'\nexpected:\n'+expectedresult
  except:
    pass
  print (testname+' '+message);
  return message == 'passed'

#Runs all of the prototype tests
def runTests(argv):
  host = 'http://dps-x509.appspot.com/'
  #host = 'http://localhost:8081/'
  if len(argv) > 1:
    host = argv[1]
  print('host: '+host) 
  #cert generated using firefox key manager
  runTest(host, 'p1', {}, 'OK');

  f = open('test.crt');
  cert = f.read();
  cert = cert.replace(' ','+')
  f.close()
  p2data = {'certificate':cert}
  p2result = cert
  runTest(host, 'p2', p2data, p2result);

if __name__ == "__main__":
  runTests(sys.argv)

